package com.simba.server.components;

import com.simba.common.log.LogUtil;
import com.simba.server.commands.impl.fetch.FetchPrinterInfoCmd;
import com.simba.server.components.data.PrinterInfo;
import org.apache.log4j.Logger;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class PrinterInfoManager
{
    private static class PrinterManagerHolder
    {
        private static final PrinterInfoManager INSTANCE = new PrinterInfoManager();
    }

    protected static final Logger logger = Logger.getLogger(PrinterInfoManager.class);

    public static PrinterInfoManager getInstance()
    {
        return PrinterManagerHolder.INSTANCE;
    }

    private final ConcurrentHashMap<String, PrinterInfo> printerInfoMap = new ConcurrentHashMap<>();

    private PrinterInfoManager()
    {

    }

    public void addPrinterInfo(PrinterInfo printerInfo)
    {
        if (printerInfo == null || printerInfo.getPrinterId() == null)
        {
            return;
        }

        this.printerInfoMap.put(printerInfo.getPrinterId(), printerInfo);
    }

    public PrinterInfo getPrinterInfo(String printerId)
    {
        if (printerId == null || "".equals(printerId))
        {
            return null;
        }

        return this.printerInfoMap.get(printerId);
    }

    public PrinterInfo[] getPrinterInfos()
    {
        return this.printerInfoMap.values().toArray(new PrinterInfo[0]);
    }

    public void loadPrinters()
    {
        try
        {
            this.printerInfoMap.clear();
            List<PrinterInfo> printerInfos = new LinkedList<>();
            CommandExecutor.executorSqlCommand(FetchPrinterInfoCmd.NAME, printerInfos,false);

            for (PrinterInfo printerInfo : printerInfos)
            {
                this.addPrinterInfo(printerInfo);
            }
        }
        catch (Exception ex)
        {
            LogUtil.LogError(PrinterInfoManager.logger, "[PrinterManager.initPrinters] Init printers info error: " + ex);
        }
    }

    public PrinterInfo removePrinterInfo(String printerId)
    {
        return this.printerInfoMap.remove(printerId);
    }
}
